<template>
  <div class="voiceCallWrapepr">
    <div class="bgAvatarWrapper" v-if="callType==='volice'">
      <div class="bgAvatar"></div>
    </div>
    {{ callType }}
    <div class="headerBtn" :class="{ fix: fix, noDrag: settingStore.fixWindow }">
        <div class="time" v-if="status===1">{{timeStr}}</div>
        <div class='menuIcon'>
          <div class="opIcon" :class="{fixActive: settingStore.fixWindow}" @click="fixWindow"><AimOutlined :style="{fontSize: '14px'}"/></div>
          <div class="opIcon" @click="minimize"><LineOutlined :style="{fontSize: '14px'}"/></div>
          <div class="opIcon close" @click="callbackPause"><CloseOutlined :style="{fontSize: '14px'}"/></div>
        </div>
    </div>
    <div class="userInfoWrapepr" v-if="callType==='volice' || (callType==='video' && status===0)">
        <img :src="avatar"/>
        <div class="name">{{roomName}}</div>
    </div>
    <div class="statusWrapper" v-if="status==0">
        <span>正在等待对方接收...</span>
    </div>
    <div class="operateWrapper">
      <!--语音通话-->
      <template v-if="callType==='volice' && status !== 2">
        <!--麦克风-->
        <div class="operate" @click='setMicrophone'>
          <div class="iconWrapper">
            <AudioFilled v-if="microphone" :style="{color: '#000', fontSize: '24px'}"/>
            <AudioMutedOutlined v-else :style="{color: '#000', fontSize: '24px'}"/>
          </div>
          <span class="text">麦克风已开</span>
        </div>
        <!--取消-->
        <div class="operate" v-if="status==0" @click="cancelCall">
          <div class="iconWrapper end">
            <PhoneFilled :style="{color: 'white', fontSize: '24px'}"/>
          </div>
          <span class="text">取消</span>
        </div>
        <!--挂断-->
        <div class="operate" v-if="status==1" @click='endCall'>
          <div class="iconWrapper end">
            <PhoneFilled :style="{color: 'white', fontSize: '24px'}"/>
          </div>
          <span class="text">挂断</span>
        </div>
        <!--扬声器-->
        <div class="operate" @click='setMicrophone'>
          <div class="iconWrapper"><SoundFilled :style="{color: '#000', fontSize: '24px'}"/></div>
          <span class="text">扬声器</span>
        </div>
      </template>
      <template v-if="callType==='video' && status !== 2">
        <!--麦克风-->
        <div class="operate" @click='setMicrophone'>
          <div class="iconWrapper">
            <AudioFilled v-if="microphone" :style="{color: '#000', fontSize: '24px'}"/>
            <AudioMutedOutlined v-else :style="{color: '#000', fontSize: '24px'}"/>
          </div>
          <span class="text">麦克风已开</span>
        </div>
        <!--扬声器-->
        <div class="operate" @click='setMicrophone'>
          <div class="iconWrapper"><SoundFilled :style="{color: '#000', fontSize: '24px'}"/></div>
          <span class="text">扬声器</span>
        </div>
        <!--摄像头-->
        <div class="operate" @click='setMicrophone'>
          <div class="iconWrapper"><VideoCameraFilled :style="{color: '#000', fontSize: '24px'}"/></div>
          <span class="text">摄像头</span>
        </div>
        <!--挂断-->
        <div class="operate" v-if="status==1" @click='endCall'>
          <div class="iconWrapper end">
            <PhoneFilled :style="{color: 'white', fontSize: '24px'}"/>
          </div>
        </div>
      </template>
    </div>
    <video v-show="callType==='video'" class="localVideo" ref="localVideo" autoplay muted></video>
    <video v-show="callType==='video'" class="remoteVideo" ref="remoteVideo" autoplay></video>
    <audio ref="audioCallRef" class="audioContainer" loop>
      <source :src="callStart" type="audio/wav" >
    </audio>
    <audio ref="audioEndRef" class="audioContainer" :autoplay="false" :loop="false" @pause="callbackPause">
      <source :src="callEnd" type="audio/wav" >
    </audio>
  </div>
</template>

<script lang="ts" setup>
// 导入工具库
import { ref, onMounted, onUnmounted } from 'vue'
import useSettingStore from '@/stores/settingStore'
import callStart from '@/assets/mp4/call.wav'
import callEnd from '@/assets/mp4/end.wav'
import { formatSecondsToTime } from '@/utils/TimeUtils.ts'
import PubSub from 'pubsub-js'
// 导入组件库
import { VideoCameraFilled, AudioFilled,PhoneFilled,SoundFilled, AimOutlined, LineOutlined,CloseOutlined, AudioMutedOutlined} from '@ant-design/icons-vue'
import { computed } from '@vue/reactivity'
import { message } from 'ant-design-vue'
import { closeVideoCallWin } from '@/utils/Electron.ts'
// 定义属性
const fix = ref<Boolean>(false)
const settingStore = useSettingStore()
const time = ref<Number>(0) // 通话时间
const status = ref<Number>(0) // 通话类型 -1未应答 0呼叫中 1通话中 2已挂断
const muted = ref<Boolean>(false) // 是否静音
const microphone = ref<Boolean>(true) // 是否开启麦克风
const audioCallRef = ref<HTMLAudioElement | null>(null) // 呼叫中语音
const audioEndRef = ref<HTMLAudioElement | null>(null)  // 关闭语音
const timeStr = computed(()=> formatSecondsToTime(time.value))
const voliceTimeInterval = ref()
const localVideo = ref(null) // 本地视频
const remoteVideo = ref(null) // 远端推流视频
const mediaStreamTrack = ref(null)
const callType = ref('volice')
const roomName = ref('')
const avatar = ref('')

// 开始语音通话
const callVoliceRtc = () => {
  if(audioCallRef.value!==null) {
    audioCallRef.value?.play()
  }
}
// 开始视频通话
const callVideoRtc = () => {
  audioCallRef.value?.play()
  if(localVideo.value!==null) {
    // 获取本地媒体流
    // 兼容代码
    window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);

    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {};
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
        var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        if (!getUserMedia) {
          return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
        }
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject);
        });
      }
    }

    //摄像头调用配置
    var mediaOpts = {
      audio: false,
      video: true,
      video: { facingMode: "environment" }, // 或者 "user"
      video: { width: 370, height: 650 }
      // video: { facingMode: { exact: "environment" } }// 或者 "user"
    }
    navigator.mediaDevices.getUserMedia(mediaOpts).then(function (stream) {
      mediaStreamTrack.value = stream;
      if ("srcObject" in localVideo.value) {
        localVideo.value.srcObject = stream
        remoteVideo.value.srcObject = stream
      } else { // 防止在新的浏览器中使用它，应为它已经不再支持了
        localVideo.value.src = window.URL && window.URL.createObjectURL(stream) || stream
        remoteVideo.value.src = window.URL && window.URL.createObjectURL(stream) || stream
      }
    }).catch(function (err) {
      alert("该设备没有摄像头")
    });
  }
}
// 设置静音状态
const setMuted = () => {
  muted.value = !muted.value
  message.open({content: !muted.value ? '已开启麦克风' : '已关闭麦克风'})
}
// 设置麦克风状态
const setMicrophone = () => {
  microphone.value = !microphone.value
  message.open({content: microphone.value ? '已静音' : '已关闭静音'})
}
// 取消通话
const cancelCall = () => {
  if(audioCallRef.value!==null) {
    audioCallRef.value?.pause()
    status.value = -1
    closeVideoCallWin()
  }
}
// 开始通话
const startCall = () => {
  status.value = 1
  voliceTimeInterval.value = setInterval(()=> {
      time.value+=1
  }, 1000)
  audioCallRef.value && audioCallRef.value.pause()
}
// 主动关闭通话
const endCall = () => {
  if(audioCallRef.value) {
    audioCallRef.value.pause()
    status.value = 2
    audioEndRef.value && audioEndRef.value.play()
    message.open({content: '已挂断'})
  }
}
// 关闭后的回调
const callbackPause = () => {
  clearInterval(voliceTimeInterval.value)
  audioCallRef.value && audioCallRef.value.pause()
  audioEndRef.value && audioEndRef.value.pause()
  closeVideoCallWin()
  callType.value = 'volice'
  time.value = 0
  status.value = 0
  microphone.value = false
}

// 生命周期
onMounted(() => {
  // 页面初始化（开始通话）
  window.api.on('main-render-chat-call', (event: any, msg: any) => {
    roomName.value = msg.roomName
    avatar.value = msg.avatar
    callType.value = msg.callType
    if(msg.callType==='volice') { // 语音通话
      callVoliceRtc()
    } else { // 视频通话
      callVideoRtc()
    }
  }); 
  // 接收到通话邀请(别人打电话给你)
  window.api.on('main-render-request-call', (event: any, msg: any) => {
  }); 
  // 对方接受通话邀请(你打电话给别人）
  window.api.on('main-render-receive-call', (event: any, msg: any) => {
  })
})

onUnmounted(() => {

})
</script>

<style lang="less" scoped>
.voiceCallWrapepr {
  height: 100%;
  width: 100%;
  // background-color: #000000bf;
  background-color: #000000;
  display: flex;
  flex-direction: column;
  align-items: center;
  -webkit-app-region: no-drag;
  border-radius: 5px;
  position: relative;
  .bgAvatarWrapper {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    background-image: url('@/assets/images/tx.jpg');
    background-size: 200% 100%;
    background-position: center;
    overflow: hidden;
    background-repeat: no-repeat;
    z-index: 0;
    filter: blur(20px);
    background-clip: padding-box;
    background-origin: padding-box;
    .bgAvatar {
      background-color: #00000096;
      height: 100%;
      width: 100%;
      z-index: 2;
    }
  }

  .localVideo {
    height: 652px;
    width: 370px;
    position: absolute;
    top: 0;
    transform: scaleX(-1);
  }
  .remoteVideo {
    height: 150px;
    width: 92.5px;
    position: absolute;
    top: 35px;
    right: 5px;
    transform: scaleX(-1);
    z-index: 2;
    border-radius: 10px;
    overflow: hidden;
  }
  .headerBtn {
    -webkit-app-region: drag;
    display: flex;
    justify-content: center;
    position: relative;
    width: 100%;
    height: 30px;
    position: fixed;
    color: #000;
    z-index: 9;
    align-items: center;
    font-size: 14px;
    color: white;
    .time {
      font-size: 15px;
    }
    &.noDrag {
      -webkit-app-region: no-drag;
    }
    &.fix {
      background-color: #e0e0e0;
      color: #7d7d7d;
      .opIcon:hover {
        background-color: #d1d1d1;
      }
    }
    .menuIcon {
      position: absolute;
      right: 0;
      height: 100%;
      align-items: center;
      -webkit-app-region: no-drag;
      display: flex;
      justify-content: space-between;
      align-items: center;
      top: 1px;
      .opIcon {
        &:hover {
          background-color: #3838383d;
 
        }
        &.close:hover {
          background-color: rgba(255, 0, 0, 0.562) !important;
          color: white;
        }
        &.fixActive {
          background-color: rgba(255, 0, 0, 0.562) !important;
        }
        display: flex;
        align-items: center;
        justify-content: center;
        width: 35px;
        height: 100%;
      }
    }
   }
  .userInfoWrapepr {
    margin-top: 40%;
    z-index: 2;
    img {
      width: 95px;
      border-radius: 10px;
    }
    .name {
      font-size: 16px;
      color: white;
      margin-top: 10px;
      text-align: center;
    }
  }
  .statusWrapper {
    margin-top: 3%;
    font-size: 13px;
    color: white;
    z-index: 2;
  }
  .operateWrapper {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 25%;
    display: flex;
    flex-direction: row;
    z-index: 2;
    align-items: center;
    flex-wrap: wrap;
    justify-content: center;
    margin-bottom: 2%;
    .operate {
      width: 33%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 5px;
      .iconWrapper {
        width: 58px;
        height: 58px;
        background-color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        &.end {
          background-color: #e75e58;
        }
      }
      .text {
          color: white;
          font-size: 12px;
        }
    }
  }
  .audioContainer {
    opacity: 0;
  }
}
</style>